import { Router } from '@angular/router';
import { environment } from './../../../../environments/environment';
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { HttpErrorResponse } from '@angular/common/http';
import { throwError } from 'rxjs';
import { catchError, retry } from 'rxjs/operators';
import { HttpHeaders } from '@angular/common/http';
import { NzModalService } from 'ng-zorro-antd/modal';

@Injectable()
export class HttpClientService {

    //API地址前缀
    public baseUrl = environment.Api;
    public resourceUrl = environment.resourceUrl;

    //默认请求头
    public httpOptions = {
        headers: new HttpHeaders({
            'Content-Type': 'application/json',
        })
    };

    constructor(
        private router: Router,
        private http: HttpClient,
        private modal: NzModalService
    ) { }

    /**
     * 自定义请求头
     * @param headers 请求头
     */
    setHeader(headers: any) {

        for (const key in headers) {
            if (headers.hasOwnProperty(key)) {
                const element = headers[key];
                this.httpOptions.headers = this.httpOptions.headers.set(key, element);
            }
        }
    }

    /**
     * post请求 （自定义头可用该方法）
     * @param reqdata 请求参数
     * @param url 请求地址
     * @param headers 请求头
     */
    post(reqdata: any, url: string | string[], headers?: undefined) {

        let _url = this.baseUrl + url;

        //自定义请求头
        // if (headers) {
        //     this.setHeader(headers);
        // }

        return this.http.post(_url, reqdata, this.httpOptions)
            .pipe(
                catchError(this.handleError)
            );
    }

    /**
     * get请求
     * @param url 请求地址
     */
    get(url: string) {

        // let _url = this.resourceUrl + url;
        let _url = this.baseUrl + url;

        if (url.indexOf("http") != -1) {
            _url = url;
        }

        return this.http.get(_url)
            .pipe(
                catchError(this.handleError)
            );
    }

    // 异常拦截
    private handleError(error: HttpErrorResponse) {

        this._error(error);

        return throwError(error);
    };

    /**
   * 默认异常处理
   * @param err 异常对象体
   */
    private _error(err: { status?: any; error: any; }) {

        let msg = err.error;

        this.modal.error({
            nzTitle: msg.title || "提示",
            nzContent: msg.detail || "网络异常,请稍后重试"
        });

        //认证异常
        if (msg.status == 403 && msg.title == "无效的刷新令牌") {
            this.router.navigate(['login']);
        }
    }
}
